package com.liwc.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liwc.constant.StatusCode;
import com.liwc.dao.SysRoleMapper;
import com.liwc.dto.CodeDto;
import com.liwc.dto.RoleDto;
import com.liwc.message.ResponseMessage;
import com.liwc.model.SysCode;
import com.liwc.model.SysMenuTree;
import com.liwc.model.SysRole;
import com.liwc.service.RoleService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
 * 
 * 模块：基于RBAC的基础权限框架demo
 * 描述：
 * @author liwc
 * @date 2018年3月25日 下午10:03:35
 * @ RoleServiceImpl
 */
@Service
public class RoleServiceImpl implements RoleService {

	private static final Log log = LogFactory.getLog(RoleServiceImpl.class);
	
	@Autowired
	private SysRoleMapper dao;

	
	
	
	@Override
	public RoleDto findById(Integer id) {
		
		if(null == id){
			return new RoleDto();
		}
		
		SysRole menu = dao.selectByPrimaryKey(id);

		RoleDto dto = new RoleDto();

		try {
			BeanUtils.copyProperties(dto, menu);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}

		return dto;
	}

	@Override
	public PageInfo<SysRole> findAll(RoleDto dto) {
		
		PageHelper.startPage(dto.getPage(), dto.getRows());
		
		List<SysRole> list = dao.selectAll(dto);
		
		PageInfo<SysRole> pi = new PageInfo<SysRole>(list);
		
		return pi;
	}

	@Override
	public List<SysRole> findAllWithChild() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<SysMenuTree> selectTreeMenu() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ResponseMessage save(SysRole resource) {
		if(null != resource.getId() ){
			dao.updateByPrimaryKeySelective(resource);
		}else{
			dao.insertSelective(resource);
		}
		
		return new ResponseMessage(StatusCode.OK, "保存成功", resource);
	}

	@Override
	public ResponseMessage deleteById(Integer id) {
		dao.deleteByPrimaryKey(id);
		return new ResponseMessage(StatusCode.OK, "删除成功", id);
	}

	@Override
	public List<SysRole> getRootList() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<SysRole> getByExample(RoleDto dto) {
		
		return dao.selectAll(dto);
	}

	@Override
	public ResponseMessage saveRoleMenu(Integer id, RoleDto dto, JSONArray arr) {

		for(int i=0; i<arr.size(); i++){
			
			dao.saveRoleMenu(id, arr.getJSONObject(i).getString("id"));
		}
		return new ResponseMessage(StatusCode.OK, "操作成功", id);
	}

	
	
	
	

}
